<template>
    <div class="container">
        <div class="heade">
            <div class="header">
                <span class="text">基本信息</span>
                <el-button style="float: right; margin-right: 20px; font-size: 14px; margin-top: 6px;"
                    @click="isDisabled = !isDisabled" :disabled="false">{{ isDisabled ? '编辑' : '保存'
                    }}</el-button>
                <span style="float: right; margin-right: 50px;font-size: 14px;">订单号: {{ salesOrders.id + 1000000 }}</span>
            </div>
            <div class="heade-text">
                <el-form ref="form" :model="salesOrders" label-width="80px" class="heade-form">
                    <el-form-item label="订单类型:">
                        <el-select v-model="salesOrders.orderType" placeholder="请选择订单类型" style="width: 160px;"
                            :disabled="isDisabled">
                            <el-option label="普通订单" value="普通订单"></el-option>
                            <el-option label="退货订单" value="退货订单"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户名称">
                        <el-input v-model="salesOrders.customerName" placeholder="请输入客户名称" style="width: 160px;"
                            :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item label="客户类型">
                        <el-input v-model="salesOrders.customerType" placeholder="请输入客户类型" style="width: 160px;"
                            :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item label="业务员">
                        <el-input v-model="salesOrders.employee" placeholder="请输入业务员" style="width: 160px;"
                            :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item label="出货仓库">
                        <el-input v-model="salesOrders.warehouse" placeholder="请输入出货仓库" style="width: 160px;"
                            :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <br />
                    <el-form-item label="发货日期">
                        <el-col :span="11">
                            <el-date-picker type="date" placeholder="选择日期" v-model="salesOrders.deliveryDate"
                                style="width: 160px;" :disabled="isDisabled"></el-date-picker>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="销售类型">
                        <el-select v-model="salesOrders.salesType" placeholder="请选择销售类型" style="width: 160px;"
                            :disabled="isDisabled">
                            <el-option label="车销" value="车销"></el-option>
                            <el-option label="访销" value="访销"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="配送车辆">
                        <el-input v-model="salesOrders.vehicle" placeholder="请输入配送车辆" style="width: 160px;"
                            :disabled="isDisabled"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="between">
            <div class="header">
                <span class="text">商品明细</span>
                <el-button style="float: right; margin-right: 20px; font-size: 14px; margin-top: 6px;"
                    @click="dialogVisible = true" :disabled="isDisabled">添加商品</el-button>
                <el-dialog title="添加商品" :visible.sync="dialogVisible" width="90%">
                    <div class="header">
                        <span class="text">选择商品</span>
                    </div>
                    <div class="heade-text">
                        <el-form ref="form" :model="searchGoodsForm" label-width="80px" class="heade-select">
                            <el-form-item label="输入品牌">
                                <el-input v-model="searchGoodsForm.brand" style="width: 160px;"></el-input>
                            </el-form-item>
                            <el-form-item label="选择分类">
                                <el-input v-model="searchGoodsForm.goodsType" style="width: 160px;"></el-input>
                            </el-form-item>
                            <el-form-item label="商品标题">
                                <el-input v-model="searchGoodsForm.name" style="width: 160px;"></el-input>
                            </el-form-item>
                            <el-button style="width: 160px; height: 40px;" @click="searchGoods">搜索</el-button>
                            <el-button style="width: 160px; height: 40px;" @click="resetGoodsForm">重置</el-button>
                        </el-form>
                        <div class="result">
                            <div class="header">
                                <span class="text">搜索结果</span>
                            </div>
                            <div class="between-table">
                                <el-table :header-cell-style="{ fontSize: '14px', textAlign: 'center' }"
                                    :cell-style="{ fontSize: '12px', textAlign: 'center' }" ref="multipleTable"
                                    :data="GoodsList" border tooltip-effect="dark" style="width: 100%"
                                    @selection-change="handleSelectionChange">
                                    <el-table-column label="商品名称" width="160">
                                        <template slot-scope="scope">{{ scope.row.name }}</template>
                                    </el-table-column>
                                    <el-table-column prop="lunit" label="大单位" width="160"></el-table-column>
                                    <el-table-column prop="luSupplyPrice" label="大单位单价"></el-table-column>
                                    <el-table-column prop="sunit" label="小单位"></el-table-column>
                                    <el-table-column prop="suSupplyPrice" label="小单位价格" width="160"></el-table-column>
                                    <el-table-column prop="number" label="现有库存(小单位)"></el-table-column>
                                    <el-table-column prop="option" label="操作">
                                        <template slot-scope="scope">
                                            <el-button
                                                :class="salesOrderGoods.some(item => item.id === scope.row.id) ? 'addButton' : 'column'"
                                                @click="addGood(scope)"
                                                :disabled="salesOrderGoods.some(item => item.id === scope.row.id)">
                                                {{ salesOrderGoods.some(item => item.id === scope.row.id) ? '已添加' : '添加' }}
                                            </el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div class="block">
                            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                :page-size="pageSize" layout="prev, pager, next, jumper" :total="GoodsListCopy2.length">
                            </el-pagination>
                        </div>
                    </div>
                    <span slot="footer" class="dialog-footer">
                        <el-button type="success" style="width: 100px; height: 40px; font-size: 14px;"
                            @click="dialogVisible = false">
                            保 存
                        </el-button>
                    </span>
                </el-dialog>
            </div>
            <div class="between-table">
                <el-table :header-cell-style="{ fontSize: '14px', textAlign: 'center' }"
                    :cell-style="{ fontSize: '12px', textAlign: 'center' }" :row-class-name="'fixed-row-height'"
                    ref="multipleTable" :data="salesOrderGoods" border tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column label="商品名称">
                        <template slot-scope="scope">{{ scope.row.name }}</template>
                    </el-table-column>
                    <el-table-column prop="lunit" label="大单位/价格/比率" width="140">
                        <template slot-scope="scope">
                            <span>{{ scope.row.luSupplyPrice }}/{{ scope.row.lunit }} * {{ scope.row.conversionRatio
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" width="160" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.num1" :min="0" :max="scope.row.lnum" size="small"
                                :disabled="isDisabled" @change="changeNum(scope.$index)"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sunit" label="价格/小单位" width="140">
                        <template slot-scope="scope">
                            <span>{{ scope.row.suSupplyPrice }}/{{ scope.row.sunit }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" width="160" align="center">
                        <template slot-scope="scope">
                            <el-input-number v-model="scope.row.num2" :min="1" :max="scope.row.snum" size="small"
                                :disabled="isDisabled" @change="changeNum(scope.$index)"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="total" label="金额(元)"></el-table-column>
                    <el-table-column prop="goodType" label="商品类型">
                        <template slot-scope="scope">
                            <span v-if="isDisabled" :style="{ color: scope.row.goodType === '赠品' ? 'red' : '' }">{{
                                scope.row.goodType }}</span>
                            <template v-else slot-scope="scope">
                                <el-select v-model="scope.row.goodType" placeholder="商品类型"
                                    @change="changeType(scope.$index)">
                                    <el-option label="正常" value="正常"></el-option>
                                    <el-option label="赠品" value="赠品"></el-option>
                                </el-select>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="option" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" size="small" @click="deleteGood(scope.$index)"
                                :disabled="isDisabled">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div
                style="border: 0 solid rgba(228, 228, 228, 1); border-width: 0 1px 1px 1px; height: 40px; line-height: 40px; text-align: right; padding-right: 20px;">
                <span style="margin: 15px;">商品共：</span>
                <span style="margin-right: 40px; color: red;">{{ goodsNum }}</span>
                <span style="margin-right: 5px">金额合计：</span>
                <span style="margin-right: 20px; color: red;">{{ salesOrders.total }}元</span>
            </div>
            <div class="footer">
                <div class="header">
                    <span class="text">付款信息</span>
                </div>
                <div class="heade-text">
                    <el-form ref="form" :model="salesOrders" label-width="80px" class="heade-form">
                        <el-form-item label="付款类型" class="head-br">
                            <el-select v-model="salesOrders.paymentType" placeholder="请选择支付类型" style="width: 160px;"
                                :disabled="isDisabled">
                                <el-option label="现金" value="现金"></el-option>
                                <el-option label="支付宝" value="支付宝"></el-option>
                                <el-option label="微信" value="微信"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="优惠金额" class="head-br">
                            <el-input v-model="salesOrders.discountAmount" placeholder="请输入优惠金额" style="width: 160px;"
                                :disabled="isDisabled" @change="changeDiscount"></el-input>
                        </el-form-item>
                        <span
                            style=" position: relative; top: 8px; font-size: 14px; left: 10px;font-weight: bold; font-size: 19px;">应付款金额：</span>
                        <span
                            style=" position: relative; top: 8px; font-size: 14px; left: 10px;color: red;font-weight: bold; font-size: 19px;">{{
                                salesOrders.total }}元</span>
                        <el-button type="success" style="position: absolute; right: 20px; width: 80px; height: 40px;"
                            @click="submitOrder" v-if="!isDisabled">
                            提交
                        </el-button>
                    </el-form>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { getGoodsList } from '@/api/goods.js'
import { getSalesOrdersDetail, addSalesOrders } from '@/api/sales_orders.js'
export default {
    data() {
        return {
            isDisabled: true,
            dialogVisible: false,
            salesOrders: {
                createTime: "2023-07-19T01:28:34.000+00:00",
                customerName: "客户A",
                customerType: "A",
                deliveryDate: "2023-07-06 00:00:00",
                discountAmount: "0",
                employee: "A员工",
                id: 114,
                orderType: "普通订单",
                paymentType: "现金",
                salesType: "车销",
                status: "未审核",
                total: "667.5",
                vehicle: "A车",
                warehouse: "B仓库",
            },
            searchGoodsForm: {
                brand: "",
                goodsType: "",
                name: "",
            },
            pageSize: 6,
            GoodsListCopy2: [],
            GoodsListCopy: [],
            GoodsList: [],
            salesOrderGoods: [],
            goodsNum: 0,
            multipleSelection: [],
        }
    },
    mounted() {
        let id = this.$route.query.id
        let isEdit = this.$route.query.isEdit
        if (isEdit) {
            this.isDisabled = false
        }
        this.getSalesOrders(id)
        this.findGoodsList()
    },
    methods: {
        submitOrder() {
            this.isDisabled = false
        },
        deleteGood(index) {
            //是否删除
            this.$confirm('是否删除该商品？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.salesOrderGoods.splice(index, 1)
                let { goodsNum, orderTotal } = this.salesOrderGoods.reduce((total, item) => {
                    return {
                        goodsNum: total.goodsNum + item.numAll * 1,
                        orderTotal: total.orderTotal + item.total * 1,
                    }
                }, { goodsNum: 0, orderTotal: 0 })
                this.goodsNum = goodsNum
                this.salesOrders.total = orderTotal
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        addGood(scope) {
            this.salesOrderGoods.push(
                {
                    id: scope.row.id,
                    name: scope.row.name,
                    lunit: scope.row.lunit,
                    luSupplyPrice: scope.row.luSupplyPrice,
                    sunit: scope.row.sunit,
                    suSupplyPrice: scope.row.suSupplyPrice,
                    conversionRatio: scope.row.conversionRatio,
                    number: scope.row.number,
                    num1: 0,
                    lnum: scope.row.number / scope.row.conversionRatio,
                    num2: 1,
                    snum: scope.row.number / 1,
                    total: scope.row.suSupplyPrice * 1 + scope.row.luSupplyPrice * 0,
                    goodType: '正常',
                    numAll: 1,
                }
            );
            let { goodsNum, orderTotal } = this.salesOrderGoods.reduce((total, item) => {
                return {
                    goodsNum: total.goodsNum + item.numAll * 1,
                    orderTotal: total.orderTotal + item.total * 1
                }
            }, { goodsNum: 0, orderTotal: 0 });
            this.goodsNum = goodsNum;
            this.salesOrders.total = orderTotal;
        },
        changeType(index) {
            // 正常和赠送
            // console.log(index);
            // console.log(this.salesOrderGoods[index].goodType);
            if (this.salesOrderGoods[index].goodType === '正常') {
                this.salesOrderGoods[index].total = this.salesOrderGoods[index].suSupplyPrice * this.salesOrderGoods[index].num2 + this.salesOrderGoods[index].luSupplyPrice * this.salesOrderGoods[index].num1;
            } else {
                this.salesOrderGoods[index].total = 0;
            }
            this.setNumAndTotal();
        },
        changeNum(index) {
            let numAll1 = this.salesOrderGoods[index].num1 * this.salesOrderGoods[index].conversionRatio + this.salesOrderGoods[index].num2;
            //判断库存（lnum和snum分别是大单位和小单位的选择max）
            if (numAll1 > this.salesOrderGoods[index].number && this.salesOrderGoods[index].number - this.salesOrderGoods[index].numAll > this.salesOrderGoods[index].conversionRatio) {
                this.$message({
                    message: '库存不足,已经为您分配了大单位最大库存',
                    type: 'warning'
                });
                this.salesOrderGoods[index].lnum = parseInt(this.salesOrderGoods[index].number / this.salesOrderGoods[index].conversionRatio);
                this.salesOrderGoods[index].num1 = this.salesOrderGoods[index].lnum;
                // return;
                // this.salesOrderGoods[index].snum = this.salesOrderGoods[index].num2 - 1;
            }
            else if (numAll1 > this.salesOrderGoods[index].number && this.salesOrderGoods[index].number - this.salesOrderGoods[index].numAll < this.salesOrderGoods[index].conversionRatio) {
                this.$message({
                    message: '已经为您减少了对应的小单位数量',
                    type: 'success'
                });
                this.salesOrderGoods[index].snum = this.salesOrderGoods[index].number - this.salesOrderGoods[index].num1 * this.salesOrderGoods[index].conversionRatio;
                this.salesOrderGoods[index].num2 = this.salesOrderGoods[index].snum;
            }
            this.salesOrderGoods[index].numAll = this.salesOrderGoods[index].num1 * this.salesOrderGoods[index].conversionRatio + this.salesOrderGoods[index].num2;
            if (this.salesOrderGoods[index].goodType === '正常') {
                this.salesOrderGoods[index].total = this.salesOrderGoods[index].num1 * this.salesOrderGoods[index].luSupplyPrice + this.salesOrderGoods[index].num2 * this.salesOrderGoods[index].suSupplyPrice;
            } else {
                this.salesOrderGoods[index].total = 0;
            }
            this.setNumAndTotal();
            this.salesOrderGoods[index].lnum = parseInt(this.salesOrderGoods[index].number / this.salesOrderGoods[index].conversionRatio);
            this.salesOrderGoods[index].snum = this.salesOrderGoods[index].number - this.salesOrderGoods[index].num1 * this.salesOrderGoods[index].conversionRatio;
        },
        setNumAndTotal() {
            let { goodsNum, orderTotal } = this.salesOrderGoods.reduce((total, item) => {
                return {
                    goodsNum: total.goodsNum + item.numAll * 1,
                    orderTotal: total.orderTotal + item.total * 1,
                }
            }, { goodsNum: 0, orderTotal: 0 });
            this.goodsNum = goodsNum;
            this.salesOrders.total = orderTotal - this.salesOrders.discountAmount;
        },
        changeDiscount() {
            // console.log(this.salesOrders.discountAmount);
            // 不允许输入负数
            if (this.salesOrders.discountAmount < 0) {
                this.salesOrders.discountAmount = 0;
                this.$message({
                    message: '折扣金额不能为负数',
                    type: 'warning'
                });
            }
            // 折扣金额不能大于订单总金额
            if (this.salesOrders.discountAmount > this.salesOrders.total) {
                this.salesOrders.discountAmount = this.salesOrders.total;
                this.$message({
                    message: '折扣金额不能大于订单总金额',
                    type: 'warning'
                });
            }
            this.salesOrders.total = this.salesOrderGoods.reduce((total, item) => {
                return total + item.total * 1;
            }, 0) - this.salesOrders.discountAmount;
        },
        getSalesOrders(id) {
            getSalesOrdersDetail(id).then(res => {
                // console.log(res)
                this.salesOrders = res.data.data.salesOrders
                this.salesOrderGoods = res.data.data.salesOrderGoods.map(item => {
                    return {
                        id: item.goodsId,
                        name: item.goodsName,
                        lunit: item.lunit,
                        luSupplyPrice: item.luSupplyPrice,
                        sunit: item.sunit,
                        suSupplyPrice: item.suSupplyPrice,
                        conversionRatio: item.conversionRatio,
                        number: item.goodsNumber,
                        num1: item.num1,
                        lnum: item.goodsNumber / item.conversionRatio,
                        num2: item.num2,
                        snum: item.goodsNumber / 1,
                        total: item.goodsPrice,
                        goodType: item.goodType,
                        numAll: item.goodsCount,
                    }
                })
                this.goodsNum = this.salesOrderGoods.reduce((total, item) => {
                    return total + item.numAll * 1
                }, 0)
                // console.log(this.salesOrderGoods)
            })
        },
        findGoodsList() {
            // console.log("findGoodsList");
            getGoodsList().then(res => {
                this.GoodsListCopy = res.data.data;
                this.GoodsListCopy2 = res.data.data;
                this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
                this.loading = false;
                // console.log("GoodsList", this.GoodsList);
            })
        },
        searchGoods() {
            // console.log(this.searchGoodsForm);
            // 从GoodsListCopy中筛选
            let { name, goodsType, brand } = this.searchGoodsForm;
            this.GoodsListCopy2 = this.GoodsListCopy.filter(item => {
                return item.name.indexOf(name) !== -1 && item.goodsType.indexOf(goodsType) !== -1 && item.brand.indexOf(brand) !== -1;
            });
            this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
        },
        resetGoodsForm() {
            this.searchGoodsForm = {
                brand: "",
                goodsType: "",
                name: "",
            };
            this.GoodsListCopy2 = this.GoodsListCopy;
            this.GoodsList = this.GoodsListCopy2.slice(0, this.pageSize);
        },
        submitOrder() {
            if (this.salesOrders.customerName === '' || this.salesOrders.customerType === '' || this.salesOrders.employee === '' || this.salesOrders.warehouse === '' || this.salesOrders.deliveryDate === '' || this.salesOrders.salesType === '' || this.salesOrders.vehicle === '' || this.salesOrders.paymentType === '') {
                this.$message({
                    message: '请填写完整信息',
                    type: 'warning'
                })
                return;
            }
            if (this.salesOrderGoods.length === 0) {
                this.$message({
                    message: '请添加商品',
                    type: 'warning'
                })
                return;
            }
            this.$confirm('确定提交订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.salesOrders.deliveryDate = this.dateFormatByEl(this.salesOrders.deliveryDate.toLocaleString().split('/').join('-'))
                // console.log(this.salesOrders);
                const salesOrderGoodsForm = this.salesOrderGoods.map(item => {
                    return {
                        id: item.id,
                        name: item.name,
                        count: item.numAll,
                        price: item.total,
                        num1: item.num1,
                        num2: item.num2,
                        goodType: item.goodType,
                    }
                })
                console.log(this.salesOrders, salesOrderGoodsForm);
                // salesOrderGoodsForm转为json字符串
                // salesOrderGoodsForm = JSON.stringify(salesOrderGoodsForm)
                // console.log(JSON.stringify(salesOrderGoodsForm));
                addSalesOrders(this.salesOrders, JSON.stringify(salesOrderGoodsForm)).then(res => {
                    console.log(res);
                    if (res.data.data === "修改销售订单成功") {
                        this.$message({
                            message: '提交成功',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消提交'
                });
            });
        },
        dateFormatByEl(date) {
            // date = 2023-7-8 00:00:00月和日小于10的时候，前面加0
            var date1 = date.split(' ')[0].split('-')
            var date2 = date.split(' ')[1]
            var month = date1[1] < 10 ? '0' + date1[1] : date1[1]
            var day = date1[2] < 10 ? '0' + date1[2] : date1[2]
            date = date1[0] + '-' + month + '-' + day + ' ' + date2
            return date
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
            this.GoodsList = this.GoodsListCopy2.slice((val - 1) * this.pageSize, val * this.pageSize);
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    }
}

</script>

<style scoped>
.heade-text {
    border: 1px solid rgba(228, 228, 228, 1);
    text-align: center;
}

.heade-form {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    top: 12px;
}

.heade-select {
    display: flex;
    position: relative;
    top: 25px;
}

.head-br {
    display: block;
}

.text {
    font-size: 14px;
    position: absolute;
    left: 12px;
}

.info1 {
    font-size: 14px;
    position: absolute;
    right: 70px;
    top: 14px;
}

.info {
    font-size: 14px;
    position: absolute;
    right: 12px;
    top: 14px;
}

.header {
    position: relative;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: rgba(243, 243, 243, 1);
    border: 1px solid rgba(228, 228, 228, 1);
}

.between .header {
    margin-top: 20px;
}

.column {
    font-size: 14px;
    margin-right: 5px;
}

.result {
    padding: 15px;
}

.end span {
    font-size: 14px;
    margin: 10px;
}

.fixed-row-height {
    height: 50px;
}
</style>